package com.example.autorefreshbussines.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class SwaggerHandlerProviderFix {

    @Autowired
    public SwaggerHandlerProviderFix(List<WebMvcRequestHandlerProvider> providers) {
        for (WebMvcRequestHandlerProvider provider : providers) {
            customizeHandlerMappings(getHandlerMappings(provider));
        }
    }

    private void customizeHandlerMappings(List<Object> mappings) {
        List<Object> copy = mappings.stream()
                .filter(mapping -> {
                    try {
                        var parserMethod = mapping.getClass().getMethod("getPatternParser");
                        return parserMethod.invoke(mapping) == null;
                    } catch (Exception e) {
                        return false;
                    }
                })
                .collect(Collectors.toList());
        mappings.clear();
        mappings.addAll(copy);
    }

    private List<Object> getHandlerMappings(WebMvcRequestHandlerProvider provider) {
        try {
            Field field = WebMvcRequestHandlerProvider.class.getDeclaredField("handlerMappings");
            field.setAccessible(true);
            return (List<Object>) field.get(provider);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


